﻿using AutoMapper;
using B.S.Traceability.Domain;
using B.S.Traceability.Error;
using B.S.Traceability.Infrastructure.Interface;
using B.S.Traceability.Writer.API.Application.Commends.Company;
using MediatR;

namespace B.S.Traceability.Writer.API.Application.CommendHandlers.Company
{
/*    public class CreateFirmsCommendHandlers : IRequestHandler<CreateFirmsCommends, APIResult<Companys>>
    {
        public Task<APIResult<Companys>> Handle(CreateFirmsCommends request, CancellationToken cancellationToken)
        {
            throw new NotImplementedException();
        }
    }*/


    public class CreateFirmsCommendHandlers : IRequestHandler<CreateFirmsCommends, APIResult<Companys>>
    {
        private readonly IBaseRepository<Companys> companysRepository;
        private readonly IMapper mapper;

        public CreateFirmsCommendHandlers(IBaseRepository<Companys> companysRepository, IMapper mapper)
        {
            this.companysRepository = companysRepository;
            this.mapper = mapper;
        }



        /// <summary>
        /// 添加企业信息
        /// </summary>
        /// <param name="request"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        public async Task<APIResult<Companys>> Handle(CreateFirmsCommends request, CancellationToken cancellationToken)
        {
            APIResult<Companys> result = new APIResult<Companys>();
            var exit = companysRepository.GetAllAsync().Result.FirstOrDefault(x => x.CompanyId == request.CompanyId);

            if (exit == null)
            {
                result.Code = APIEnum.添加成功;
                result.Msg = "添加成功";

                var farm = mapper.Map<Companys>(request);

                farm.BatchId = request.BatchId;

                farm.IsDel = false;
                await companysRepository.Add(farm);
            }
            else
            {
                mapper.Map(request, exit);
                await companysRepository.Update(exit);
               // exit.CompanyId = request.CompanyId;
                exit.CompanyName = request.CompanyName;
                exit.ProvinceId = request.ProvinceId;
                exit.CityId = request.CityId;
                exit.CountyId = request.CountyId;
                exit.CompanyAddres = request.CompanyAddres;
                exit.Foundedtime = request.Foundedtime;
                exit.Companyinfo = request.Companyinfo;
                result.Code = APIEnum.修改成功;
                result.Msg = "修改成功";


            
            }

          
            return await Task.FromResult(result);
        }
    }
}
